package com.bdqn.t313.dom4j;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * 使用DOM4j解析XML文档
 */
public class Dom4jParseXML {

    public static void main(String[] args) throws DocumentException, IOException {
        //1、获取Document对象
        SAXReader reader = new SAXReader();
        Document document = reader.read("XMLParse_ch02/src/main/resources/book.xml");
        //2、获取节点相关内容
        //获取文档根元素
        Element rootElement = document.getRootElement();
        //获取根节点下的子节点
        List<Element> book = rootElement.elements("book");
        System.out.println(book.get(0).attributeValue("id"));
        //获取子节点
        Element title = book.get(0).element("title");
        System.out.println(title.getText());

        //添加子节点
        //Element author = book.get(0).addElement("price");
        //author.setText("￥15");

        //修改price子节点
        //修改前先将price节点删除
        Element price = book.get(0).element("price");
        price.setText("￥38");
        price.addAttribute("name","价格");


        //将文档写入XML
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("XMLParse_ch02/src/main/resources/book.xml"));
        xmlWriter.write(document);
        xmlWriter.close();
        System.out.println("保存成功！");

    }

}
